import {Button, Canvas, Image, ScrollView, Text, View} from '@tarojs/components'
import Taro, {useDidShow, useRouter} from '@tarojs/taro'
import type React from 'react'
import {useCallback, useEffect, useRef, useState} from 'react'
// 引入 weapp-qrcode
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-expect-error
import drawQrcode from 'weapp-qrcode'
import {getOrder, type Order} from '@/api'
import {createPaymentV3} from '@/api/paymentV3'
import {getCachedOpenId} from '@/utils/wechat'

const OrderDetail: React.FC = () => {
  const router = useRouter()
  const orderNo = router.params.orderNo as string

  const [order, setOrder] = useState<Order | null>(null)
  const [loading, setLoading] = useState(true)
  const [qrCodes, setQrCodes] = useState<Map<number, string>>(new Map())
  const [paying, setPaying] = useState(false)
  const _canvasRefs = useRef<Map<number, string>>(new Map())

  const loadData = useCallback(async () => {
    if (!orderNo) return

    setLoading(true)
    try {
      const result = await getOrder(orderNo)

      if (result.success && result.data) {
        setOrder(result.data)
      } else {
        Taro.showToast({
          title: result.error || '加载失败',
          icon: 'none'
        })
      }
    } catch (error) {
      console.error('加载订单详情失败:', error)
      Taro.showToast({
        title: '加载失败，请重试',
        icon: 'none'
      })
    } finally {
      setLoading(false)
    }
  }, [orderNo])

  // 生成二维码
  const generateQRCode = useCallback(async (code: string, ticketId: number) => {
    try {
      const canvasId = `qrcode-canvas-${ticketId}`

      // 等待 Canvas 渲染
      await new Promise((resolve) => setTimeout(resolve, 100))

      // 使用 weapp-qrcode 生成二维码
      drawQrcode({
        canvasId,
        text: code,
        width: 200,
        height: 200,
        typeNumber: -1,
        correctLevel: 1,
        background: '#ffffff',
        foreground: '#000000'
      })

      // 将 Canvas 转换为图片
      await new Promise((resolve) => setTimeout(resolve, 300))

      const res = await Taro.canvasToTempFilePath({
        canvasId,
        width: 200,
        height: 200,
        destWidth: 200,
        destHeight: 200
      })

      if (res.tempFilePath) {
        setQrCodes((prev) => new Map(prev).set(ticketId, res.tempFilePath))
      }
    } catch (error) {
      console.error('生成二维码失败:', error)
    }
  }, [])

  useDidShow(() => {
    loadData()
  })

  useEffect(() => {
    if (order?.tickets && order.status === 'paid') {
      // 为每张票生成二维码
      for (const ticket of order.tickets) {
        generateQRCode(ticket.verification_code, ticket.id)
      }
    }
  }, [order?.tickets, order?.status, generateQRCode])

  const formatDate = (dateStr: string) => {
    const date = new Date(dateStr)
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
  }

  const formatExhibitionDate = (dateStr: string) => {
    const date = new Date(dateStr)
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
  }

  const getStatusText = (status: string) => {
    switch (status) {
      case 'pending':
        return '待支付'
      case 'paid':
        return '已支付'
      case 'cancelled':
        return '已取消'
      default:
        return status
    }
  }

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'pending':
        return 'text-yellow-600 bg-yellow-50'
      case 'paid':
        return 'text-green-600 bg-green-50'
      case 'cancelled':
        return 'text-red-600 bg-red-50'
      default:
        return 'text-gray-600 bg-gray-50'
    }
  }

  const handlePay = async () => {
    if (!order) return

    setPaying(true)
    try {
      // 获取用户 openid（使用缓存机制）
      const openid = await getCachedOpenId()

      // 创建支付订单（使用 API V3）
      const paymentResult = await createPaymentV3(order.order_no, openid)

      if (!paymentResult.success) {
        Taro.showToast({
          title: paymentResult.error || '创建支付订单失败',
          icon: 'none'
        })
        return
      }

      // 调用微信支付
      const payParams = paymentResult.data

      await Taro.requestPayment({
        timeStamp: payParams.timeStamp,
        nonceStr: payParams.nonceStr,
        package: payParams.package,
        signType: payParams.signType,
        paySign: payParams.paySign
      })

      // 支付成功
      Taro.showToast({
        title: '支付成功',
        icon: 'success'
      })

      // 重新加载订单数据
      setTimeout(() => {
        loadData()
      }, 1500)
    } catch (error: any) {
      console.error('支付失败:', error)

      // 用户取消支付
      if (error.errMsg?.includes('cancel')) {
        Taro.showToast({
          title: '已取消支付',
          icon: 'none'
        })
      } else {
        Taro.showToast({
          title: error.errMsg || '支付失败',
          icon: 'none'
        })
      }
    } finally {
      setPaying(false)
    }
  }

  if (loading) {
    return (
      <View className="min-h-screen flex items-center justify-center bg-gradient-to-b from-blue-50 to-blue-100">
        <Text className="text-gray-500">加载中...</Text>
      </View>
    )
  }

  if (!order) {
    return (
      <View className="min-h-screen flex items-center justify-center bg-gradient-to-b from-blue-50 to-blue-100">
        <Text className="text-gray-500">订单不存在</Text>
      </View>
    )
  }

  return (
    <View style={{background: 'linear-gradient(to bottom, #eff6ff, #dbeafe)', minHeight: '100vh'}}>
      <ScrollView scrollY style={{background: 'transparent'}} className="box-border h-screen">
        <View className="p-4 pb-32">
          {/* 订单状态 */}
          <View className="bg-white rounded-2xl shadow-sm p-4 mb-4">
            <View className="flex items-center justify-center">
              <View className={`px-4 py-2 rounded-full ${getStatusColor(order.status)}`}>
                <Text className="text-sm font-medium">{getStatusText(order.status)}</Text>
              </View>
            </View>
          </View>

          {/* 展览信息 */}
          <View className="bg-white rounded-2xl shadow-sm p-4 mb-4">
            <Text className="text-base font-bold text-gray-900 block mb-4">展览信息</Text>
            <View className="space-y-2">
              <View>
                <Text className="text-lg font-bold text-gray-900 block">{order.exhibition_title}</Text>
              </View>
              <View>
                <Text className="text-sm text-gray-600">地点：{order.exhibition_location}</Text>
              </View>
              <View>
                <Text className="text-sm text-gray-600">
                  时间：{order.start_date && formatExhibitionDate(order.start_date)} 至{' '}
                  {order.end_date && formatExhibitionDate(order.end_date)}
                </Text>
              </View>
            </View>
          </View>

          {/* 票种明细 */}
          <View className="bg-white rounded-2xl shadow-sm p-4 mb-4">
            <Text className="text-base font-bold text-gray-900 block mb-4">票种明细</Text>
            <View className="space-y-3">
              {order.items?.map((item) => (
                <View
                  key={item.id}
                  className="flex items-center justify-between py-2 border-b border-gray-100 last:border-0">
                  <View className="flex-1">
                    <Text className="text-sm font-medium text-gray-900 block">{item.ticket_type_name}</Text>
                    <Text className="text-xs text-gray-500 block mt-1">
                      ¥{item.price} × {item.quantity}
                    </Text>
                  </View>
                  <Text className="text-base font-bold text-gray-900">¥{Number(item.subtotal).toFixed(2)}</Text>
                </View>
              ))}
              <View className="flex items-center justify-between pt-3 border-t-2 border-gray-200">
                <Text className="text-base font-bold text-gray-900">总计</Text>
                <Text className="text-xl font-bold text-blue-600">¥{Number(order.total_amount).toFixed(2)}</Text>
              </View>
            </View>
          </View>

          {/* 购票人信息 */}
          <View className="bg-white rounded-2xl shadow-sm p-4 mb-4">
            <Text className="text-base font-bold text-gray-900 block mb-4">购票人信息</Text>
            <View className="space-y-2">
              <View className="flex items-center justify-between">
                <Text className="text-sm text-gray-500">姓名</Text>
                <Text className="text-sm text-gray-900">{order.buyer_name}</Text>
              </View>
              <View className="flex items-center justify-between">
                <Text className="text-sm text-gray-500">手机号</Text>
                <Text className="text-sm text-gray-900">{order.buyer_phone}</Text>
              </View>
              <View className="flex items-center justify-between">
                <Text className="text-sm text-gray-500">身份证号</Text>
                <Text className="text-sm text-gray-900">{order.buyer_id_card}</Text>
              </View>
            </View>
          </View>

          {/* 订单信息 */}
          <View className="bg-white rounded-2xl shadow-sm p-4 mb-4">
            <Text className="text-base font-bold text-gray-900 block mb-4">订单信息</Text>
            <View className="space-y-2">
              <View className="flex items-center justify-between">
                <Text className="text-sm text-gray-500">订单号</Text>
                <Text className="text-sm text-gray-900">{order.order_no}</Text>
              </View>
              <View className="flex items-center justify-between">
                <Text className="text-sm text-gray-500">下单时间</Text>
                <Text className="text-sm text-gray-900">{formatDate(order.created_at)}</Text>
              </View>
            </View>
          </View>

          {/* 电子票（每张票单独显示） */}
          {order.status === 'paid' && order.tickets && order.tickets.length > 0 && (
            <View className="bg-white rounded-2xl shadow-sm p-4 mb-4">
              <Text className="text-base font-bold text-gray-900 block mb-4">电子票</Text>
              <View className="space-y-6">
                {order.tickets.map((ticket, index) => {
                  const qrCodeUrl = qrCodes.get(ticket.id)
                  const canvasId = `qrcode-canvas-${ticket.id}`

                  return (
                    <View key={ticket.id} className="border border-blue-200 rounded-xl p-4">
                      <View className="flex items-center justify-between mb-3">
                        <Text className="text-sm font-bold text-blue-600">
                          {ticket.ticket_type_name} - 第{index + 1}张
                        </Text>
                        <View className="px-2 py-1 bg-green-50 rounded">
                          <Text className="text-xs text-green-600">{ticket.is_used ? '已使用' : '未使用'}</Text>
                        </View>
                      </View>

                      {/* 游客信息 */}
                      <View className="bg-gray-50 rounded-lg p-3 mb-3">
                        <Text className="text-xs text-gray-500 block mb-2">游客信息</Text>
                        <View className="space-y-1">
                          <View>
                            <Text className="text-xs text-gray-600">姓名：{ticket.visitor_name}</Text>
                          </View>
                          <View>
                            <Text className="text-xs text-gray-600">手机号：{ticket.visitor_phone}</Text>
                          </View>
                          <View>
                            <Text className="text-xs text-gray-600">身份证号：{ticket.visitor_id_card}</Text>
                          </View>
                        </View>
                      </View>

                      {/* 二维码 */}
                      <View className="flex flex-col items-center">
                        {/* Canvas 用于生成二维码（隐藏） */}
                        <Canvas
                          canvasId={canvasId}
                          style={{width: '200px', height: '200px', position: 'absolute', left: '-9999px'}}
                        />

                        {/* 显示生成的二维码图片 */}
                        {qrCodeUrl ? (
                          <View className="bg-white p-3 rounded-lg border border-blue-200">
                            <Image src={qrCodeUrl} mode="aspectFit" className="w-48 h-48" />
                          </View>
                        ) : (
                          <View className="w-48 h-48 flex items-center justify-center bg-gray-100 rounded-lg">
                            <Text className="text-gray-500 text-xs">生成中...</Text>
                          </View>
                        )}

                        <View className="mt-3 bg-blue-50 px-3 py-2 rounded-lg">
                          <Text className="text-xs text-gray-600 block mb-1 text-center">验票码</Text>
                          <Text className="text-base font-bold text-blue-600 text-center tracking-wider">
                            {ticket.verification_code}
                          </Text>
                        </View>
                        <Text className="text-xs text-gray-500 mt-2 text-center">请在展览入口处出示此二维码验票</Text>
                      </View>
                    </View>
                  )
                })}
              </View>
            </View>
          )}
        </View>
      </ScrollView>

      {/* 底部支付按钮 */}
      {order.status === 'pending' && (
        <View className="fixed bottom-0 left-0 right-0 bg-white border-t border-gray-200 p-4 safe-area-inset-bottom">
          <View className="flex items-center justify-between">
            <View>
              <Text className="text-xs text-gray-500 block">应付金额</Text>
              <Text className="text-xl font-bold text-blue-600 block mt-1">
                ¥{Number(order.total_amount).toFixed(2)}
              </Text>
            </View>
            <Button
              size="default"
              className="px-8 py-3 bg-blue-600 text-white rounded-full font-medium text-base break-keep"
              onClick={handlePay}
              disabled={paying}>
              {paying ? '支付中...' : '立即支付'}
            </Button>
          </View>
        </View>
      )}
    </View>
  )
}

export default OrderDetail
